package com.ewanghuiju.app.ui.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.App;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.app.ForegroundCallbacks;
import com.ewanghuiju.app.base.RootActivity;
import com.ewanghuiju.app.base.contract.home.SearchShopResultContract;
import com.ewanghuiju.app.model.bean.response.PintuanShopListResponBean;
import com.ewanghuiju.app.presenter.home.SearchShopResultPresenter;
import com.ewanghuiju.app.ui.home.adapter.SearchShopResultAdapter;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanShopDetailsActivity;
import com.ewanghuiju.app.util.ClipboardUtils;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.widget.popupwindow.CommonSearchPopup;
import com.ewanghuiju.app.widget.popupwindow.PopupItemClickCallback;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 搜索商品结果页面
 * @time 2020/2/17
 */
//注册路由，当下发的jmlink key与此处的“jmlink_key”一致时，跳转到此页面。checkYYB状态后，应用宝可通过此方法获取参数信息
//@JMLinkRouter(keys = "ewhjlink_shopinfo")
public class SearchShopResultActivity extends RootActivity<SearchShopResultPresenter> implements SearchShopResultContract.View, ForegroundCallbacks.Listener {
    @BindView(R.id.toolbar)
    LinearLayout mToolbar;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.view_main)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_screen_jg)
    TextView tvScreenJg;
    @BindView(R.id.tv_screen_xl)
    TextView tvScreenXl;
    @BindView(R.id.tv_screen_zh)
    TextView tvScreenZh;
    @BindView(R.id.iv_screen_jg)
    ImageView ivScreenJg;
    @BindView(R.id.iv_screen_xl)
    ImageView ivScreenXl;
    @BindView(R.id.tv_screen_rs)
    TextView tvScreenRs;
    @BindView(R.id.iv_screen_rs)
    ImageView ivScreenRs;

    private SearchShopResultAdapter searchShopResultAdapter;

    private int currentPage = 1;

    private int spe_price = 0;

    private int sales = 0;

    private int people_number = 0;

    private String searchText = "";

    private CommonSearchPopup commonSearchPopup;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_searchshop_result;
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        // 注册监听
        ForegroundCallbacks.get(App.getInstance()).addListener(this);
        searchText = getIntent().getStringExtra(Constants.SEARCH_BODY);
        onInit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        searchText = intent.getStringExtra(Constants.SEARCH_BODY);
        onInit();
    }

    /**
     * 初始跳转加载
     */
    private void onInit() {
        if (!TextUtils.isEmpty(searchText)) {
            tvSearch.setText(searchText);
        }
        LoadingDialogUtils.show(mContext);
        currentPage = 1;
        mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
        setRecyleview();
    }


    //    private void register(Context context){
//        JMLinkAPI.getInstance().registerDefault(new JMLinkCallback() {
//            @Override
//            public void execute(Map<String, String> paramMap, Uri uri) {
////                JMLinkIntentBuilder.buildIntent(paramMap, context, DefaultRouteActivity.class);
//                LogUtil.e("AAAAA  DefaultRouteActivity paramMap"+new Gson().toJson(paramMap)+"URL:"+new Gson().toJson(uri));
//            }
//        });
//        // jmlinkKey:  jmlink 的 key, jmlink的唯一标识
//        JMLinkAPI.getInstance().register("ewhjlink_shopinfo", new JMLinkCallback() {
//            public void execute(Map<String, String> paramMap, Uri uri) {
////                JMLinkIntentBuilder.buildIntent(paramMap, context, SecondActivity.class);
//                LogUtil.e("AAAAA  paramMap"+new Gson().toJson(paramMap)+"URL:"+new Gson().toJson(uri));
//            }
//        });
//    }
//
//    private static void unregister() {
//        JMLinkAPI.getInstance().unregisterDefault();
//        JMLinkAPI.getInstance().unregister("ewhjlink_shopinfo");
//    }


    @Override
    protected void intSmartRefreshLayout() {
//        super.intSmartRefreshLayout();
        refreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        refreshLayout.setEnableLoadMore(true);//是否启用上拉加载功能
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(mContext);
                currentPage++;
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(mContext);
                currentPage = 1;
                refreshLayout.resetNoMoreData();
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
            }
        });
    }


    public void setRecyleview() {
//        List<ResultShopListResponBean> mList = TestBean.getResultShopListResponBeanList(15);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mLinearLayoutManager.setSmoothScrollbarEnabled(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);
//        pintuanShopListAdapter = new SearchResultShopListAdapter(R.layout.item_result_shop_list);
        searchShopResultAdapter = new SearchShopResultAdapter(new ArrayList<>());
        searchShopResultAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PintuanShopListResponBean pintuanShopListResponBean = (PintuanShopListResponBean) adapter.getItem(position);
                if (pintuanShopListResponBean.getItemType() == PintuanShopListResponBean.RESULT_TYPE_SHOP) {
                    //商品
                    new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
                            pintuanShopListResponBean.getId())
                            .startActivity(true);
                } else if (pintuanShopListResponBean.getItemType() == PintuanShopListResponBean.RESULT_TYPE_TUAN) {
                    //团
                    new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
                            pintuanShopListResponBean.getGoods_id())
                            .putExtra(Constants.PINTUAN_SEARCH_TYPE, 2)
                            .putExtra(Constants.PINTUAN_SEARCH_MOUDE, pintuanShopListResponBean)
                            .putExtra(Constants.PINTUAN_USER_YES, pintuanShopListResponBean.getUser_yes())
                            .startActivity(true);
                }
            }
        });
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(searchShopResultAdapter);
    }

    @OnClick({R.id.layout_zh, R.id.layout_jg, R.id.layout_xl, R.id.layout_rs})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
//        String etStr = etSearch.getText().toString().trim();
        currentPage = 1;
        LoadingDialogUtils.show(mContext);
        switch (view.getId()) {
            case R.id.layout_zh:
                reSetScreen();
                spe_price = 0;
                people_number = 0;
                sales = 0;
                tvScreenZh.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
                break;
            case R.id.layout_jg:
                reSetScreen();
                people_number = 0;
                sales = 0;
                tvScreenJg.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                if (spe_price == 1) {
                    spe_price = 2;
                    ivScreenJg.setImageResource(R.mipmap.icon_screen_down);
                } else {
                    spe_price = 1;
                    ivScreenJg.setImageResource(R.mipmap.icon_screen_up);
                }
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
                break;
            case R.id.layout_rs:
                reSetScreen();
                spe_price = 0;
                sales = 0;
                tvScreenRs.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                if (people_number == 1) {
                    people_number = 2;
                    ivScreenRs.setImageResource(R.mipmap.icon_screen_down);
                } else {
                    people_number = 1;
                    ivScreenRs.setImageResource(R.mipmap.icon_screen_up);
                }
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
                break;
            case R.id.layout_xl:
                reSetScreen();
                spe_price = 0;
                people_number = 0;
                tvScreenXl.setTextColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
                if (sales == 2) {
                    sales = 1;
                    ivScreenXl.setImageResource(R.mipmap.icon_screen_up);
                } else {
                    sales = 2;
                    ivScreenXl.setImageResource(R.mipmap.icon_screen_down);
                }
                mPresenter.getdata(currentPage, TextUtils.isEmpty(searchText) ? "" : searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.iv_back, R.id.go_search})
    public void doBack(View view) {
        if (AntiShake.check(view.getId())) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressedSupport();
                break;
            case R.id.go_search:
                new StartActivityUtil(mContext, SearchShopActivity.class).putExtra(Constants.SEARCH_INPUT_BODY,
                        TextUtils.isEmpty(searchText) ? "" : searchText)
                        .startActivity(true);
                break;
            default:
                break;
        }

    }

    /**
     * 重置顶部筛选
     */
    public void reSetScreen() {
        tvScreenZh.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        tvScreenJg.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        tvScreenRs.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        tvScreenXl.setTextColor(ContextCompat.getColor(mContext, R.color.color_666));
        ivScreenJg.setImageResource(R.mipmap.icon_screen_normal);
        ivScreenRs.setImageResource(R.mipmap.icon_screen_normal);
        ivScreenXl.setImageResource(R.mipmap.icon_screen_normal);
    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .titleBar(mToolbar, true)
                .statusBarDarkFont(true)
                .init();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除监听
        ForegroundCallbacks.get(App.getInstance()).removeListener(this);
        if (searchShopResultAdapter != null) {
            searchShopResultAdapter.clearCountDownTimer();
        }
    }

    @Override
    public void showContent(PintuanShopListResponBean pintuanShopListResponBean) {
        LoadingDialogUtils.dismissDialog_ios();
        if (pintuanShopListResponBean == null) {
            pintuanShopListResponBean = new PintuanShopListResponBean();
        }
        List<PintuanShopListResponBean> mList = pintuanShopListResponBean.getList();
        if (mList == null) {
            mList = new ArrayList<>();
        }

        if (pintuanShopListResponBean.getCode_type() == 1) {
            //拼团信息
            for (PintuanShopListResponBean pintuanShopListResponBean1 : mList) {
                pintuanShopListResponBean1.setItemType(PintuanShopListResponBean.RESULT_TYPE_TUAN);
            }

        } else {
            //商品信息
            for (PintuanShopListResponBean pintuanShopListResponBean1 : mList) {
                pintuanShopListResponBean1.setItemType(PintuanShopListResponBean.RESULT_TYPE_SHOP);
            }
        }
        if (currentPage == 1) {
            if (mList.size() < Constants.NUM_OF_PAGE) {
                refreshLayout.finishRefreshWithNoMoreData();
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishRefresh();
            }
            searchShopResultAdapter.setNewData(mList);
        } else {
            if (mList.size() < Constants.NUM_OF_PAGE) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
            searchShopResultAdapter.addData(mList);
        }
        if (pintuanShopListResponBean.getCode_type() == 1) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        }

        if (searchShopResultAdapter.getData().size() > 0) {
            stateMain();
        } else {
            stateEmpty();
        }
    }

    @Override
    public void showErrorContent() {
        LoadingDialogUtils.dismissDialog_ios();
        if (currentPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            currentPage--;
            refreshLayout.finishLoadMore();
        }
        if (searchShopResultAdapter.getData().size() == 0) {
            super.stateError();
        }
    }


    @Override
    public void onBecameForeground() {
        Activity mActivity = App.getInstance().getCurrentActivity();
        if (mActivity == null || !(mActivity instanceof SearchShopResultActivity)) {
            return;
        }
        //判断粘贴板是否存在内容
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                CharSequence mCharSequence = ClipboardUtils.getText();
                String clipboardText = TextUtils.isEmpty(mCharSequence) ? "" : mCharSequence.toString();
                if (clipboardText.length() > 0) {
                    ClipboardUtils.copyText("", "");
                    if (commonSearchPopup != null) {
                        commonSearchPopup.setContent(clipboardText);
                        commonSearchPopup.showPopupWindow();
                        return;
                    }
                    commonSearchPopup = new CommonSearchPopup(mContext,
                            new PopupItemClickCallback() {

                                @Override
                                public void onSureCallback(String text) {
//                                    new StartActivityUtil(mContext, SearchShopResultActivity.class).putExtra(Constants.SEARCH_BODY,
//                                            text)
//                                            .startActivity(true);
                                    if (!TextUtils.isEmpty(text)) {
                                        searchText = text;
                                        tvSearch.setText(searchText);
                                        LoadingDialogUtils.show(mContext);
                                        currentPage = 1;
                                        mPresenter.getdata(currentPage, searchText, spe_price == 0 ? "" : spe_price + "", sales == 0 ? "" : sales + "", people_number == 0 ? "" : people_number + "");
                                    }
                                }

                                @Override
                                public void onTextChangedCallback(String text) {

                                }
                            });
                    commonSearchPopup.setPopupGravity(Gravity.CENTER);
                    commonSearchPopup.setWidth(commonSearchPopup.getScreenWidth() * 2 / 3);
                    commonSearchPopup.setContent(clipboardText);
                    commonSearchPopup.showPopupWindow();
                }
            }
        }, 500);
    }

    @Override
    public void onBecameBackground() {

    }
}
